local redisConfig = require("luaScript.module.config.redis-config");
local redis = require("resty.redis");

local redisObj = redis:new();
redisObj:set_timeouts(redisConfig.timeout, redisConfig.timeout, redisConfig.timeout);

-- 连接服务器
local ok,err = redisObj:connect(redisConfig.host_name, redisConfig.port);
if not ok then
    ngx.say("failed to connect:", err);
    return;
end

-- 设置值
ok,err = redisObj:set("dog", "an animal");
if not ok then
    ngx.say("failed to set dog: ", err, "<br>")
    return
else
    ngx.say("set dog: ok", "<br>");
end

local res, err = redisObj:get("dog");
if not res or res == ngx.null then
    ngx.say("failed to get dog: ", err, "<br>");
    return;
else
    ngx.say("get dog: ok", "<br>", res, "<br>");
end

-- 批量操作，减少IO次数
redisObj:init_pipeline();
redisObj:set("cat", "cat 1");
redisObj:set("horse", "horse 1");
redisObj:get("cat");
redisObj:get("horse");
redisObj:get("dog");
local results, err = redisObj:commit_pipeline();

if not results then
    ngx.say("failed to commit the pipelined requests:", err);
end

for i, res in ipairs(results) do
    if type(res) == "table" then
        if res[1] == false then
            ngx.say("failed to run command ", i , ":", res[2], "<br>");
        else
            ngx.say("succeed to run command ", i , ":", res[i], "<br>");
        end
    else
        ngx.say("succeed to run command ", i , ":", res, "<br>");
    end
end

-- 简单的关闭redis
local ok, err = redisObj:close();
if not ok then
    ngx.say("failed to close", err);
    return;
else
    ngx.say("succeed to close redis");
end